<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Badger Controller
 *
 * The front end for Badger User Management, Authentication, Authorization library
 *
 * +- XAcms -+
 * author: Chris Lunsford
 */
class BadgerController {
	
	var $CI;
	
	function __construct() {
		$this->CI =& get_instance();
	
		//Make sure the Badger library is loaded, if not auto-loaded
		if (!class_exists('Badger')) {
		     $this->CI->load->library('Badger');
		}
		
		$this->CI->load->model('UserModel');
		$this->CI->load->model('RememberMe');
	}
	
	/*
	 * Login function displays the login form and handles the login POST data
	 *
	 */
	function login() {
		if ($this->CI->badger->isloggedin()) {
			$this->CI->UserModel->updateLastActivity($this->CI->session->userdata('username'));
			redirect('admin');
		} else {
			//User is not logged in, check to see if they should be
			$hash = $this->CI->input->cookie('cl_user', TRUE);
			$string = $this->CI->input->cookie('cl_ranstring', TRUE);
			$check = $this->CI->RememberMe->checkRememberMe($hash, $string); //grab the username or FALSE
			
			if ($check != FALSE) {
				//login the user returned from the RememberMe Check
				$this->CI->badger->login($check);
				$this->CI->UserModel->updateLastActivity($this->CI->session->userdata('username'));
				redirect('admin'); //and they are now logged in
			} else {  //process form data
				$username = $this->CI->input->post('username', TRUE);
				$password = $this->CI->input->post('password', TRUE);
				$remember = $this->CI->input->post('remember_me', TRUE);

				if ($this->CI->UserModel->validateLogin($username, $password)) {
					$this->CI->badger->login($username);
					$this->CI->UserModel->updateLastLogin($username);
					if ($remember) {
						if ($this->CI->config->item('remember_me_enabled')) {
							$this->CI->badger->addRememberMe($username);
						}
					}
				//we need to send the user to the page he was requesting
				redirect('admin');
				}
			}
		}
	}
	
	function logout() {
		$this->CI->badger->logout();
	}
	
	function register() {
		//process register data
		$this->CI->load->library('validation');
		
		$rules['username'] = "required|max_length[40]";
		$rules['password'] = "required|max_length[40]|matches[passconf]";
		$rules['passconf'] = "required";
		$rules['lastname'] = "required|max_length[100]";
		$rules['firstname'] = "required|max_length[100]";
		$rules['email'] = "required|max_length[100]|valid_email";
		$this->CI->validation->set_rules($rules);
		
		if ($this->CI->validation->run() == TRUE) {
			$this->CI->badger->register();
			
			//!! redirect them somewhere useful, perhaps the login page? !!//
			redirect('site/login');
		}
	}
		
}
?>